package com.lute.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.ide.eclipse.quickfix.jdt.processors.RequestMappingDialog.Method;
import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.json.UserNameJSON;
import com.lute.model.User;
import com.lute.utils.ServerErrorResponse;

@Controller
public class GetRegisteredUsersServlet {
	
	@RequestMapping(value="/getRegisteredUsers", method= RequestMethod.GET)
	public @ResponseBody String getRegisteredUsers(HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonRes = new JSONObject();
		
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String role = (String)session.getAttribute("role");
		
		/* check the authorization */
		if(!(role.equals("approver")) || (role.equals("clientAdmin"))) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
			result = jsonRes.toString();
			return result;
		}
		
		List<UserNameJSON> listOfUsersJSON = User.prepareUsersCredentials();
		jsonRes.put("users", listOfUsersJSON);
		
		result = jsonRes.toString();
		return result;
	}
}
